package com.boarsoft.boar.gateway.weixin.biz.impl;

import java.util.List;

import javax.annotation.PostConstruct;

import org.hibernate.query.Query;
import org.hibernate.type.StringType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.gateway.weixin.biz.WxUserBiz;
import com.boarsoft.boar.gateway.weixin.common.WeixinFactory;
import com.boarsoft.boar.gateway.weixin.common.WeixinPlatformUser;
import com.boarsoft.boar.gateway.weixin.entity.WxBinding;
import com.boarsoft.boar.gateway.weixin.entity.WxPlatformUser;
import com.google.gson.Gson;

@Transactional
@Component("weixinBiz")
public class WxUserBizImpl extends WxBizImpl implements WxUserBiz {

	private Logger log = LoggerFactory.getLogger(WxUserBizImpl.class);

	@SuppressWarnings({ "unchecked" })
	@Override
	@Transactional(readOnly = true)
	public WxBinding getByAcctNo(String fakeid, String acctNo) {
		StringBuilder hql = new StringBuilder();
		hql.append(" FROM ").append(WxBinding.class.getName());
		hql.append(" WHERE ");
		hql.append(" status = :status ");
		hql.append(" AND platformFakeId = :platformFakeId ");
		hql.append(" AND cardnum = :cardnum ");
		Query<WxBinding> query = dao.createQuery(hql.toString());
		query.setParameter("status", "0", new StringType());
		query.setParameter("platformFakeId", fakeid, new StringType());
		query.setParameter("cardnum", acctNo, new StringType());
		List<WxBinding> binding = query.list();
		if (binding != null && binding.size() > 0) {
			return binding.get(0);
		}
		return null;
	}

	@PostConstruct
	public void init() {
		try {
			loadWeixinPlatformUser();
		} catch (Exception e) {
			log.error("微信模板数据初始化加载失败...", e);
		}
	}

	@Transactional(readOnly = true)
	public void loadWeixinPlatformUser() throws Exception {
		List<WxPlatformUser> list = dao.list(WxPlatformUser.class);
		for (WxPlatformUser user : list) {
			WeixinFactory.petWeixinPlatformUser(user.getFakeId(), new WeixinPlatformUser(user));
			log.info("微信公众号数据初始化{}", new Gson().toJson(user));
		}
	}

}
